# -*- coding: utf-8 -*-
"""
Created on Mon Apr 25 14:02:20 2022

@author: 2029355M
"""

import pandas as pd
pd.set_option('display.max_columns', None)
import matplotlib.pyplot as plt
import numpy as np

import imageio


df = pd.read_csv('C:\\Users\\YOUR PATH\\carbon.csv')

df = df[-120:] # get the last 120 months
df = df.reset_index(drop=True)


x = df.index
y = df.CI

# smooth x-y plot 
from scipy import interpolate
x_new = np.linspace(1, max(x), 5000)
a_BSpline = interpolate.make_interp_spline(x, y)
y_new = a_BSpline(x_new)

# for plot text later on
year = np.linspace(2012+5/12, 2022+4/12, 5000)


deg = 360*max(x)/12
deg = np.linspace(0, -deg, len(x_new))
deg = deg -1*360/12

deg = deg * 2*np.pi/360

# convert to polar coordinates
x_cord = y_new*np.cos(deg)
y_cord = y_new*np.sin(deg)
z = (x_cord**2 + y_cord**2)**0.5



fig, ax = plt.subplots(figsize=(16,10), facecolor='#22768b')

# =============================================================================
# set plot
# =============================================================================

ax.set_facecolor('#22768b')
# shadow = -30

lim = 700
ax.set_ylim([-1*lim, lim])
ax.set_xlim([-1*lim, lim])
ax.set_xticks([])
ax.set_yticks([])

# Move left y-axis and bottim x-axis to centre, passing through (0,0)
# ax.spines['left'].set_position('center')
ax.spines['left'].set_color('#22768b')
# ax.spines['bottom'].set_position('center')
ax.spines['bottom'].set_color('#22768b')

# Eliminate upper and right axes
ax.spines['right'].set_color('#22768b')
ax.spines['top'].set_color('#22768b')


# Show ticks in the left and lower axes only
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

ax.tick_params(axis='x', colors='white')
ax.tick_params(axis='y', colors='white')

# text
# ax.text(660, 570, '6 month \naverage: ' + str(int(df.iloc[j].average)), fontsize = 16, color='white', ha='right', va='top')
circle1 = plt.Circle((0, 0), 600, color='white', 
                     fill=False, zorder=-10001, linewidth=2.0)


f=1.0
circle1 = plt.Circle((0, 0), 600, color='white', fill=False, zorder=-10001, linewidth=f)
ax.add_patch(circle1)
ax.text(-600, 10, '600', fontsize=16, color='white', ha='center', va='top')

circle1 = plt.Circle((0, 0), 300, color='white', fill=False, zorder=-10001, linewidth=f)
ax.add_patch(circle1)
ax.text(-300, 10, '300', fontsize=16, color='white', ha='center', va='top')

    
start = 1 #550
stop = 680
text_r = 650
num = 12
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
for m, mon in enumerate(months):
    ang = m*2*np.pi/num
    # base coords
    xb = start*np.sin(ang)
    yb = start*np.cos(ang)
    # end coords
    xe = stop*np.sin(ang) 
    ye = stop*np.cos(ang)
    # plot
    ax.plot([xb, xe], [yb, ye], color='white', linewidth=0.5, alpha=1)
    # text
    offset = -2.5 * 2*np.pi/360
    ang_deg = 90 - ang*360/(2*np.pi)
    if ang_deg < -90:
        ang_deg = ang_deg + 180
    xt = text_r*np.sin(ang+offset)
    yt = text_r*np.cos(ang+offset)
    ax.text(xt, yt, mon, rotation=ang_deg, ha='center', va='center', fontsize = 16, color='white')

plt.tight_layout()

ax.set_aspect('equal', adjustable='box')

ax.set_title('UK Grid Carbon Intensity', color='white', rotation='vertical',
              x=-0.1,y=0.5, fontsize=32, ha='center', va='center')
ax.text(-770, 0, 'All units $gCO_2/kWh$', rotation=90, color='white',
             fontsize=24, ha='center', va='center')

# =============================================================================
# plot data
# =============================================================================

step = 15

from matplotlib import cm
z = z - z.min() # move to 0
reds = cm.get_cmap('Reds', z.max())
colors = []
for r in z:
    colors.append(reds(int(r)))

# ax.plot(x_cord, y_cord, c='k', linewidth=5.5, zorder=0)
# # ax.plot(x_cord, y_cord, c='#ea8c9b', linewidth=5.0)
# ax.scatter(x_cord, y_cord, c=reds(z), s=2.5, zorder=1)


for i in np.arange(1, len(x_cord)-1, step):
    print(i)
    ax.plot(x_cord[i+1:i+step], y_cord[i+1:i+step], c='k', linewidth=6.0, zorder=i)
    ax.plot(x_cord[i:i+step], y_cord[i:i+step], c=colors[i], linewidth=5.0, zorder=i+100)
    
    if x_cord[i] == 0.0:
        if y_cord[i] > 0.0:
            print(i)
    # add shadow
    # ax.plot(x_cord[i:i+2]+shadow, y_cord[i:i+2]+shadow, c='k', linewidth=8, zorder=i-100, alpha=0.2)
    
    circle1 = plt.Circle((603, 603), 100, color='#22768b', fill=True, linewidth=f, zorder=i)
    ax.add_patch(circle1)
    ax.text(600, 600, str(int(year[i])), fontsize = 22, color='white', ha='center', va='center', zorder=i+1)
    
    save_dir = 'C:\\YOUR RAW IMAGE SAVE LOCATION'
    
    if i < 10 :
        plt.savefig(save_dir+'0000'+str(i)+'.png')
    elif i < 100 :
        plt.savefig(save_dir+'000'+str(i)+'.png')
    elif i < 1000 :
        plt.savefig(save_dir+'00'+str(i)+'.png')
    elif i < 10000:
        plt.savefig(save_dir+'0'+str(i)+'.png')
    else:
        plt.savefig(save_dir + str(i)+'.png')
    # plt.close()
    plt.show()
# plt.show()
    
    
# ax.plot(x_cord, y_cord, c='k', linewidth=5.5, zorder=500)
# ax.plot(x_cord, y_cord, c='#ea8c9b', linewidth=5.0, zorder=1000)


# =============================================================================
# GIF making
# =============================================================================


import os
files = os.listdir(save_dir)

images = []
for file_name in sorted(os.listdir(save_dir)):
    if file_name.endswith('.png'):
        file_path = os.path.join(save_dir, file_name)
        images.append(imageio.imread(file_path))
imageio.mimsave('C:\\YOUR GIF SAVE LOCATION\\GIF_carbon.gif', images)



